package com.googlecode.chelonia;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class AfricaXmlRpc {

	private static Map<String, MapImage> sessions = new HashMap<String, MapImage>();
	private static Random random = new Random();

	public String create(int width, int height) {
		String key = "ik" + random.nextLong();
		sessions.put(key, new MapImage(width, height));
		return key;
	}

	public String setBackground(String key, String color) {
		MapImage i = sessions.get(key);
		i.setBackground(new Color(Integer.parseInt(color, 16)));
		return key;
	}
	
	public String paintCountries(String key, String color, String countriesList){
		CountrySet countries = new CountrySet(countriesList);
		Color col = new Color(Integer.parseInt(color, 16));
		MapImage i = sessions.get(key);
		i.paintCountries(col, countries);
		return key;
	}

	public String paintBorders(String key, String color, String countriesList, double lineWidth){
		CountrySet countries = new CountrySet(countriesList);
		Color col = new Color(Integer.parseInt(color, 16));
		MapImage i = sessions.get(key);
		i.paintBorders(col, countries, (float)lineWidth);
		return key;
	}
	
	public byte[] toImage(String key, String extension){
		MapImage mi = sessions.remove(key);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		mi.toImage(extension, baos);
		byte[] data = baos.toByteArray();
		try {
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

}
